package com.qy.controller.app;

import com.qy.base.core.*;
import com.qy.model.Message;
import com.qy.service.MessageService;
import com.github.pagehelper.PageHelper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController
@RequestMapping("app/message")
public class MessageController {
    @Resource
    private MessageService messageService;

    @PostMapping("/add")
    public Result add(@RequestBody Message message) {
        messageService.save(message);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        messageService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Message message) {
        messageService.update(message);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Message message = messageService.findById(id);
        return ResultGenerator.successResult(message);
    }

    @GetMapping("/list")
    public Result list(PageBean<Message> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Message> list = messageService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //首页未读消息数量
    @GetMapping("/unreadMessageNumber")
    public Result unreadMessageNumber(Message message) {
        if (message.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Integer number = messageService.selectUnreadMessageNumber(message);
        return ResultGenerator.successResult(number);
    }

    //消息通知
    @GetMapping("/messageList")
    public Result messageList(PageBean<Message> page, Message message) {
        if (message.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Message> list = messageService.selectMessageByUser_id(message);
        for (int i = 0; i < list.size(); i++) {
            Message message1 = list.get(i);
            message1.setMessage_state(2);
            messageService.update(message1);
        }
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

}
